package com.example.login.controller;

import com.example.login.entity.Collect;
import com.example.login.entity.Poem;
import com.example.login.repository.CollectRepository;
import com.example.login.repository.PoemRepository;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/collect")
public class CollectController {
    @Resource
    private CollectRepository collectRepository;
    @Resource
    private PoemRepository poemRepository;

    @PostMapping("/showcollect/{userid}")  //路径后加上当前用户的id
    public Map showcollect(@PathVariable Integer userid){
       List<Collect> collectList = collectRepository.findByUserid(userid);
        Map<Integer,List<Poem>> map = new HashMap<>();
        for (int i=0;i<collectList.size();i++) {
           map.put(i, poemRepository.findById(collectList.get(i).getPoemid()));
       }
        return map;
    }

    @PostMapping("/addcollect/{id}")
    public Collect addcollect(@RequestBody BigInteger poemid, @PathVariable Integer id){
        Collect collect = new Collect();

        System.out.println(poemid);
        System.out.println(id);

        if (collectRepository.findByUseridAndPoemid(id,poemid)==null) {
            collect.setUserid(id);
            collect.setPoemid(poemid);
            collect = collectRepository.save(collect);
            return collect;
        }
        collectRepository.deleteByUseridAndPoemid(id,poemid);
        return null;
    }

}
